package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.CartAddUuBean;
import com.atguigu.realtime.bean.UserLoginBean;
import com.atguigu.realtime.bean.UserRegisterBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.joni.constants.Reduce;

import java.time.Duration;

/**
 * com.atguigu.realtime.app.dws.Dws_05_DwsUserUserRegisterWindow
 * 用户域用户注册各窗口汇总表
 * 从 DWD 层用户注册表中读取数据，统计各窗口注册用户数，写入 Doris。
 */
public class Dws_05_DwsUserUserRegisterWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_05_DwsUserUserRegisterWindow().init(
                4005,
                2,
                "Dws_05_DwsUserUserRegisterWindow",
                Constant.TOPIC_DWD_USER_REGISTER
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        stream
                .map(JSON::parseObject)
                // 找到某个用户的第一条加购记录
                .keyBy(obj -> obj.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, UserRegisterBean>() {

                    private ValueState<String> registerState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        registerState = getRuntimeContext().getState(new ValueStateDescriptor<String>("RegisterState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject obj,
                                               Context ctx,
                                               Collector<UserRegisterBean> out) throws Exception {
                        // 业务数据中的ts是 秒, 所以要 * 1000

                        Long ts = obj.getLong("ts") * 1000;
                        String today = AtguiguUtil.toDate(ts);
                        if (!today.equals(registerState.value())) {
                            // 这个用户的今天第一次注册
                            registerState.update(today);

                            out.collect(new UserRegisterBean("", "",
                                    "",
                                    1L,
                                    ts));
                        }

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserRegisterBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean, ts) -> bean.getTs())
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<UserRegisterBean>() {
                            @Override
                            public UserRegisterBean reduce(UserRegisterBean bean1,
                                                           UserRegisterBean bean2) throws Exception {
                                bean1.setRegisterCt(bean1.getRegisterCt() + bean2.getRegisterCt());
                                return bean1;
                            }
                        },
                        new ProcessAllWindowFunction<UserRegisterBean, UserRegisterBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx,
                                                Iterable<UserRegisterBean> elements,
                                                Collector<UserRegisterBean> out) throws Exception {
                                UserRegisterBean bean = elements.iterator().next();

                                bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));

                                bean.setCurDate(AtguiguUtil.toDate(System.currentTimeMillis()));


                                out.collect(bean);
                            }
                        }
                )
                .map(bean -> {

                    SerializeConfig conf = new SerializeConfig();
                    conf.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
                    return JSON.toJSONString(bean, conf);

                })
                //.print("sink");
                .addSink(FlinkSinkUtil.getDorisSink("gmall2022.dws_user_user_register_window"));
    }
}
